package com.example.team.controller;

import com.example.team.entity.Test;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 对外提供数据导出服务接口类
 *
 */
@Controller
public class ExcelController {
    @ResponseBody
    @GetMapping(value = "/toExcel",
            produces = "text/html;charset=UTF-8")
    public String getExcel(){
        System.out.println("进入导出后端方法");
        Test test =new Test();
        test.setId(1);
        test.setName("admin");
        test.setPassword("123");
        String[]titles={"主键","姓名","密码"};
        HSSFWorkbook workbook=new HSSFWorkbook();
        HSSFSheet sheet=workbook.createSheet("用户表");
        HSSFRow titleRow=sheet.createRow(0);
        for(int i=0;i<titles.length;i++){
            HSSFCell cell=titleRow.createCell(i);
            cell.setCellValue(titles[i]);
        }
        HSSFRow row=sheet.createRow(1);
        row.createCell(0).setCellValue(test.getId());
        row.createCell(1).setCellValue(test.getName());
        row.createCell(2).setCellValue(test.getPassword());
        try{
            workbook.write(new FileOutputStream("D:/file/用户表.xls"));
        }catch (IOException e){
            System.out.println(e.getMessage());
        }
        return "导出文件成功";
    }
}
